package version4.common.serializer.MyCode;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import version4.common.Message.MessageType;
import version4.common.serializer.MySerializer.Serializer;

import java.util.List;

public class MyDecoder extends ByteToMessageDecoder {
    /**
     * @param ctx 上下文
     * @param in 输入缓冲区，用于存储接收到的消息
     * @param list 输出列表，用于存储解码后的消息对象
     */
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> list) throws Exception {
        short messageType = in.readShort();
        if(messageType != MessageType.REQUEST.getCode() && messageType!= MessageType.RESPONSE.getCode()){
            System.out.println("消息类型错误");
            return;
        }
        short serializerType = in.readShort();
        Serializer serializer = Serializer.getSerializer(serializerType);
        if(serializer == null){
            throw new RuntimeException("序列化器不存在");
        }
        // 数据长度
        int length = in.readInt();
        byte[] bytes = new byte[length];
        in.readBytes(bytes);
        Object object = serializer.deserialize(bytes, messageType);
        list.add(object);
    }
}
